// store/modules/wordList.js
import { createStore } from 'vuex';
import {parseCsv} from "../utils.js";
import axios from "axios";
// import * as actions from '../actions.js';
// import * as mutations from '../mutations.js';


const state = () => ({
  currentWordList: [],
  currentWordListFileName: 'default.csv'
});

const mutations = {
  setWordList(state, wordList) {
    state.currentWordList = wordList;
  },
  setWordListFileName(state, fileName) {
    state.currentWordListFileName = fileName;
  },
  UPDATE_WORD_STATUS(state, { word, status }) {
    const word_tmp = state.currentWordList.find(w => w.word === word);
    if (word_tmp) {
      word_tmp.status = status;
    }
  },

  SET_WORD_DETAILS  (state, { word, details })  {
    console.log('Setting word details for word:', word, 'with details:', details);

    if (!details || !Array.isArray(details) || details.length === 0) {
      console.error('Details is undefined or empty');
      return;
    }
    const word_ = state.currentWordList.find(w => w.word === word);
    if (word_) {
      // 更新音标
      const phonetics = details[0].phonetics;
      const phonetic = phonetics.find(p => p.text)?.text || '';
      word_.phonetic = phonetic;

      const meanings = details[0].meanings;
      const definition = meanings[0]?.definitions[0]?.definition || '';
      word_.definition = definition;

      word_.chineseDefinition = details[0].chineseDefinition;
    }
  }

};

const actions = {
  async loadDefaultWordList({ commit }) {
    try {
      const response = await fetch('/default.csv');
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const text = await response.text();
      const wordList = parseCsv(text);
      commit('setWordList', wordList);
    } catch (error) {
      console.error('加载默认单词表失败:', error);
    }
  },
  changeWordList({ commit }, { fileName, wordList }) {
    commit('setWordList', wordList);
    commit('setWordListFileName', fileName);
  },
  updateWordStatus({ commit }, { word, status })  {
    commit('UPDATE_WORD_STATUS', { word, status });
  },

  // handleSuccessfulResponse (commit, word, wordDetails) {
  //   console.log('Handling successful response for word:', word, 'with details:', wordDetails);
  //   if (wordDetails && Array.isArray(wordDetails) && wordDetails.length > 0) {
  //     commit('SET_WORD_DETAILS', { word, details: wordDetails });
  //   } else {
  //     console.error('Word details are undefined or empty');
  //   }
  // },

  async fetchWordDetails  ({ commit }, word)  {
    try {
      //API_URL = 'https://api.dictionaryapi.dev/api/v2/entries/en/';
      console.log('Fetching word details for:', word);
      let API_URL = 'https://api.dictionaryapi.dev/api/v2/entries/en/';
      const response = await axios.get(`${API_URL}${word}`);
      const details = response.data;
     // console.log(details);
      //this.handleSuccessfulResponse(commit, word, details);
      console.log('Handling successful response for word:', word, 'with details:', details);
      if (details && Array.isArray(details) && details.length > 0) {
        commit('SET_WORD_DETAILS', { word, details: details });
      } else {
        console.error('Word details are undefined or empty');
      }
      return true; // 返回成功标志
    } catch (error) {
      console.error('Failed to fetch word details:', error);
      // 可以在这里添加更多的错误处理逻辑
      return false; // 返回失败标志
    }
  }
};

const getters = {
  getCurrentWordList: state => state.currentWordList,
  getCurrentWordListFileName: state => state.currentWordListFileName
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
};
